package com.chens.common.security;

import com.chens.payload.ApiResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 自定义认证入口点
 * @description 用于处理未认证请求（未登录/token失效）,返回401未授权状态码和JSON格式的错误信息(
 * @author chensh
 * @date 2025/08/01 16:22
 */

@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        
        ApiResponse<?> apiResponse = ApiResponse.error(HttpStatus.UNAUTHORIZED.value(), "认证失败：" + authException.getMessage());
        response.getWriter().write(new ObjectMapper().writeValueAsString(apiResponse));
    }
}